clear all
set more off

do "set_path.do"

global analysis ${outdir}usd_analysis/
global temp 	${analysis}temp/
global graphs 	${analysis}graphs/

cap mkdir $graphs
cap mkdir $temp
cap mkdir "${outdir}usd_analysis"
cap mkdir "${outdir}usd_analysis/level"
cap mkdir "${outdir}usd_analysis/beta"

global GEN_DATA		1
global GEN_TAB4		1
global GEN_TAB5		1
global GEN_FIG5		1
global GEN_FIG6		1
global GEN_FIGA2	1
global OVERWRITE 	1	// For overwriting calculation in Tables 4,5

***** I. GENERATE DATA SET *****

if $GEN_DATA {

*** I.1. Import Broad Dollar, VIX, S&P500, IG Spread ***
/*
* Pull Broad Dollar, VIX, SPX, and IG Spread from FRED 	
do "set_fred_key.do"
import fred DTWEXBGS VIXCLS SP500 BAMLC0A0CM, aggregate(daily, eop)  nosummary clear
rename daten date
drop datestr

* Merge with SPX data from another source
mmerge date using ${datadir}other/index_data.dta, type(1:1) unmatch(master) uname(_)
replace DTWEXBGS = _broaddollar if missing(DTWEXBGS) & !missing(_broaddollar)
replace VIXCLS = _vix if missing(VIXCLS) & !missing(_vix)
replace SP500 = _sp500 if missing(SP500) & !missing(_sp500)
drop _*

save ${datadir}other/vix_usd.dta, replace
*/

*** I.2. Generate CIP weekly & daily datasets ***

use "${datadir}cip_all_both.dta", clear

mmerge date using "${datadir}other/vix_usd.dta", type(n:1) unmatch(master)
gen cip_rf=(r-r_usd-rho)*100

gen week = wofd(date)
format week %tw
collapse (lastnm) cip_govt cip_rf y y_usd r r_usd DTWEXBGS VIXCLS SP500 BAMLC0A0CM, by (group currency tenor week)
collapse (mean) cip_govt cip_rf y y_usd r r_usd DTWEXBGS VIXCLS SP500 BAMLC0A0CM, by (group tenor week) cw

egen id=group(group tenor)
tsset id week
local ch 1

gen log_vix=log(VIXCLS)
gen log_brusd=log(DTWEXBGS)
gen log_spx=log(SP500)
gen ig=BAMLC0A0CM

gen ss = r - y
gen ss_usd = r_usd - y_usd

foreach x in cip_rf cip_govt log_brusd log_vix log_spx ig ss ss_usd {
	bys id: gen d_`x'=`x' - `x'[_n-`ch']
}

label var d_cip_govt "U.S. Treasury Premium"
label var d_cip_rf "Benchmark CIP"
label var d_log_brusd "Broad Dollar Index"
label var d_ss "Foreign Swap Spread"
label var d_ss_usd "U.S. Swap Spread"

save "${temp}/merge_week.dta", replace
}

***** II. Tab 4: Decomposition of Government CIP Deviations *****

if ${GEN_TAB4} {

capture program drop component_stats
program define component_stats
	args tenor dvar window

	use "${temp}/merge_week.dta", clear
	
	rename DTWEXBGS brusd
	
	replace ss = ss*100
	replace ss_usd = ss_usd*100
	
	capture drop included _date
	gen included = (tenor=="`tenor'") & !missing(cip_rf) & !missing(cip_govt) & !missing(ss) & !missing(ss_usd)
	
	gen _date = dofw(week)
	gen con = 1
	
	eststo: newey2 `dvar' con if group=="g10" & year(_date) >= 2010 & year(_date) <= 2015 & included, lag(`window') force nocons
	eststo: newey2 `dvar' con if group=="g10" & year(_date) >= 2016 & year(_date) <= 2020 & included, lag(`window') force nocons
	eststo: newey2 `dvar' con if group=="g10" & year(_date) >= 2021 & year(_date) <= 2025 & included, lag(`window') force nocons
end

local window = 26
foreach dvar in cip_govt cip_rf ss ss_usd brusd {
	if "`dvar'" == "brusd" {
		local tenors 3m
	}
	else {
		local tenors 3m 1y 5y 10y
	}
	
	foreach tenor in `tenors' {
		local filename = "${analysis}/level/level_week_`dvar'_`tenor'.tex"
		capture confirm file `filename'
		if (_rc != 0) | ${OVERWRITE} {			
			eststo clear

			disp("week - `dvar' - `ivar' - `tenor'")
			component_stats `tenor' `dvar' `window'
			
			if "`dvar'" == "brusd"     		label var con "Broad Dollar Index"
			else if "`dvar'" == "cip_rf"	label var con "Benchmark CIP - `tenor'"
			else if "`dvar'" == "cip_govt"	label var con "UST Premium - `tenor'"
			else if "`dvar'" == "ss"		label var con "For. Swap Spread - `tenor'"
			else if "`dvar'" == "ss_usd"	label var con "U.S. Swap Spread - `tenor'"
			else label var con "Error"

			esttab est* using "${analysis}/level/level_week_`dvar'_`tenor'.tex", k(con) starlevels(* 0.10 ** 0.05 *** 0.01) b(%7.2f) se label noobs nonumber nomtitles style(tex) fragment substitute(\_ _) prehead("") nolines booktabs compress nogaps replace
		}
		else {
			disp("`filename' already exists; move on")
		}

	}
}
}

***** III. Tab 5: Beta on VIX *****

if ${GEN_TAB5} {
	
capture program drop rollingreg
program define rollingreg
	args tenor dvar ivar window

	use "${temp}/merge_week.dta", clear
	
	replace d_log_brusd = d_log_brusd * 100
	replace d_ss = d_ss * 100
	replace d_ss_usd = d_ss_usd * 100
	
	capture drop included _date
	gen included = tenor=="`tenor'"	
	replace included = included & !missing(cip_rf) & !missing(cip_govt) & !missing(ss) & !missing(ss_usd)
	
	gen _date = dofw(week)
	
	* Change independent var so we can stack different regressions on the same row
	capture drop _temp_ivar
	gen _temp_ivar = `ivar'
	
	eststo: newey2 `dvar' _temp_ivar if group=="g10" & year(_date) >= 2010 & year(_date) <= 2015 & included, lag(`window') force
	eststo: newey2 `dvar' _temp_ivar if group=="g10" & year(_date) >= 2016 & year(_date) <= 2020 & included, lag(`window') force
	eststo: newey2 `dvar' _temp_ivar if group=="g10" & year(_date) >= 2021 & year(_date) <= 2025 & included, lag(`window') force
end


*** Aggregate Regression
local window = 26
foreach dvar in d_log_brusd d_cip_rf d_cip_govt d_ss d_ss_usd {
	if "`dvar'" == "d_log_brusd" {
		local tenors 3m
	}
	else {
		local tenors 3m 1y 5y 10y
	}

	foreach tenor in `tenors' {
		local filename = "${analysis}beta/beta_week_`dvar'_`tenor'.tex"
		capture confirm file `filename'
		if (_rc != 0) | ${OVERWRITE} {
			eststo clear
			foreach ivar in d_log_vix d_log_spx d_ig {
				disp("week - `dvar' - `ivar' - `tenor'")
				rollingreg `tenor' `dvar' `ivar' `window'
			}

			local lbl : var label `dvar'

			if "`dvar'" == "d_log_brusd"     label var _temp_ivar "Broad Dollar Index"
			else if "`dvar'" == "d_cip_rf"   label var _temp_ivar "Benchmark CIP - `tenor'"
			else if "`dvar'" == "d_cip_govt" label var _temp_ivar "UST Premium - `tenor'"
			else if "`dvar'" == "d_ss"		 label var _temp_ivar "For. Swap Spread - `tenor'"
			else if "`dvar'" == "d_ss_usd"	 label var _temp_ivar "U.S. Swap Spread - `tenor'"
			else label var _temp_ivar "Error"

			esttab est* using "${analysis}beta/beta_week_`dvar'_`tenor'.tex", k(_temp_ivar) starlevels(* 0.10 ** 0.05 *** 0.01) b(%7.2f) se label noobs nonumber nomtitles style(tex) fragment substitute(\_ _) prehead("") nolines booktabs compress nogaps replace
		}
		else {
			disp("`filename' already exists; move on")
		}

	}
}
}

***** IV. Fig 5: Beta on VIX *****

if ${GEN_FIG5} {
	
global tenors	"1y 5y"
global lhs		"d_cip_rf d_cip_govt d_log_brusd"

local y			"d_log_vix"
local horizon	104
local oldpath	"`c(pwd)'"

foreach tenor in $tenors {
	use "${temp}/merge_week.dta", clear
	
	cd ${temp}
	foreach x in $lhs {
		rolling _b _se r2=e(r2), window(`horizon') step(1) saving(week_`x'_`y'_`tenor'_`horizon', replace): regress `x' `y' if group=="g10" & tenor=="`tenor'", vce(robust)
	}
	cd `oldpath'	
	
	foreach x in $lhs {
		use "${temp}/week_`x'_`y'_`tenor'_`horizon'", clear
		drop _b_cons _se_cons

		rename _b_`y' beta_`x'_`y'
		rename _se_`y' se_`x'_`y'
		rename _eq2_r2 r2_`x'_`y'
		gen horizon=`horizon'
		gen tenor="`tenor'"
		save "${temp}/week_`x'_`y'_`tenor'_`horizon'_clean.dta", replace
	}
	
	use "${temp}/week_d_log_brusd_d_log_vix_`tenor'_`horizon'_clean.dta", clear
	foreach x in $lhs {
		mmerge id start end using "${temp}/week_`x'_`y'_`tenor'_`horizon'_clean.dta", type(1:1)
	}
	
	replace beta_d_log_brusd_d_log_vix=beta_d_log_brusd_d_log_vix*100

	twoway (line beta_d_log_brusd_d_log_vix end, lcolor(green) lwidth(medthick)) ///
		   (line beta_d_cip_rf_d_log_vix end, lcolor(red) lwidth(medthick) lpattern(dash)) ///
		   (line beta_d_cip_govt_d_log_vix end, lwidth(medthick) lcolor(blue) lpattern(shortdash)) if end>=tw(2006w1), ///
		   legend(pos(6) order(1 "Broad Dollar" 2 "Benchmark CIP" 3 "Government CIP") size(medium) rows(1)) ///
		   yline(0, lcolor(grey) lstyle(solid)) ytitle("Beta on VIX", size(medlarge)) ///
		   name("beta_nose_long_`horizon'_`tenor'", replace) xtitle("") ///
		   ylabel(,labsize(medlarge) nogrid) tla(2005w1(260)2025w1, format(%twCCYY) nogrid) xsize(6) ysize(4)
	graph export "${graphs}beta_nose_long_`horizon'_`tenor'.png", replace
}
}


**********************
*CURRENCY BY CURRENCY*
**********************
if ${GEN_FIG6} {

use "${datadir}cip_all_both.dta", clear

mmerge date using "${datadir}other/vix_usd.dta", type(n:1) unmatch(master)
gen cip_rf=(r-r_usd-rho)*100

* Generate weekly data
gen week =wofd(date)
format week %tw
collapse (lastnm) cip_govt cip_rf y y_usd r r_usd spot_norm DTWEXBGS VIXCLS SP500 BAMLC0A0CM, by (group currency tenor week)

egen id=group(group currency tenor)
tsset id week

* Calculate relevant statistics
gen log_vix=log(VIXCLS)
gen log_brusd=log(DTWEXBGS)
gen log_spx=log(SP500)
gen log_spot=log(spot_norm)
gen ig=BAMLC0A0CM

gen ss = r - y
gen ss_usd = r_usd - y_usd

foreach x in cip_rf cip_govt log_spot log_brusd log_vix log_spx ig ss ss_usd {
	bys id: gen d_`x'= d.`x'
}

label var d_cip_govt "U.S. Treasury Premium"
label var d_cip_rf "Benchmark CIP"
label var d_log_spot "Dollar Exchange Rate"
label var d_log_brusd "Broad Dollar Index"
label var d_ss "Foreign Swap Spread"
label var d_ss_usd "U.S. Swap Spread"

save "${temp}merge_week_panel.dta", replace

use "${temp}merge_week_panel.dta", clear

global lhs "d_cip_rf d_cip_govt d_log_spot"

local tenor 1y
levelsof(curr), local(currlist)

foreach x in $lhs {
	foreach tp in 1 2 3 {
		gen beta_`x'_d_log_vix_1y_`tp'=0
		
		foreach c in `currlist' {
			if `tp'==1 {
				local startyear=2010
				local endyear=2015
			}
			if `tp'==2 {
				local startyear=2016
				local endyear=2020
			}
			if `tp'==3 {
				local startyear=2021
				local endyear=2025
			}
			
			cap{
				reg `x' d_log_vix if currency=="`c'" & tenor=="`tenor'" & yofd(dofw(week))>=`startyear' & yofd(dofw(week))<=`endyear', r
				replace beta_`x'_d_log_vix_1y_`tp'=_b[`y'] if currency=="`c'" 
			}
		}
	}
}

collapse (firstnm) beta*, by(group currency tenor)

foreach x in beta_d_log_spot_d_log_vix_1y_1 beta_d_log_spot_d_log_vix_1y_2 beta_d_log_spot_d_log_vix_1y_3 {
	replace `x'=`x'*100
}

foreach x in beta_d_cip_govt_d_log_vix beta_d_cip_rf_d_log_vix beta_d_log_spot_d_log_vix {
	twoway (scatter `x'_1y_3 `x'_1y_1, mlabel(curr) mlabcolor(midgreen) mcolor(green)) (lfit `x'_`tenor'_3 `x'_`tenor'_3, lc(orange) range(-5,15)) if group=="g10", xtitle("Beta, 2010-2015") ytitle("Beta, 2021-2025") xline(0,lpattern(dash) lcolor(gray)) yline(0,lpattern(dash) lcolor(gray)) legend(off) name("`x'_`tenor'",replace)  xsize(4) ysize(4) 
	graph export "${graphs}/`x'_`tenor'_change.png", replace
}

foreach x in beta_d_cip_govt_d_log_vix_1y beta_d_cip_rf_d_log_vix_1y beta_d_log_spot_d_log_vix_1y {
twoway (scatter `x'_3 `x'_1, mlabel(curr)) (lfit `x'_3 `x'_3, range(-5,15)), xtitle("Beta, 2010-2015") ytitle("Beta, 2021-2025") xline(0,lpattern(dash) lcolor(gray)) yline(0,lpattern(dash) lcolor(gray)) legend(off) name("`x'",replace) title("`x'") 
}

twoway (scatter beta_d_cip_rf_d_log_vix_1y_3 beta_d_cip_rf_d_log_vix_1y_1, mlabel(curr)) (lfit beta_d_cip_rf_d_log_vix_1y_3 beta_d_cip_rf_d_log_vix_1y_3, range(-5,15)) if group=="g10", xtitle("Beta, 2010-2015") ytitle("Beta, 2021-2025") xline(0,lpattern(dash) lcolor(gray)) yline(0,lpattern(dash) lcolor(gray)) legend(off) 

}


if ${GEN_FIGA2}{

global lhs "d_cip_rf"
global rhs ="d_cip_govt"
global tenors "3m 1y 5y"
local  horizon 260

use "${temp}/merge_week.dta", clear
local oldpath	"`c(pwd)'"

cd ${temp}
foreach x in $lhs {
	foreach y in $rhs {
		foreach tenor in $tenors {
		rolling _b _se r2=e(r2), window(`horizon') step(1) saving(`x'_`y'_`tenor'_`horizon'_week, replace): regress `x' `y' if group=="g10" & tenor=="`tenor'", r
	}
}
}
cd `oldpath'

foreach x in $lhs {
	foreach y in $rhs {
		foreach tenor in $tenors {			
			use ${temp}`x'_`y'_`tenor'_`horizon'_week, clear
			drop _b_cons _se_cons
			rename _b_`y' beta_`x'_`y'
			rename _se se_`x'_`y'
			rename _eq2_r2 r2_`x'_`y'
			gen horizon=`horizon'
			gen tenor="`tenor'"
			save ${temp}`x'_`y'_`tenor'_`horizon'_week_clean.dta, replace
		}
	}
}

foreach x in $lhs {
	foreach y in $rhs {
		clear
		foreach tenor in $tenors {	
			append using ${temp}`x'_`y'_`tenor'_`horizon'_week_clean.dta
		}
		save ${temp}`x'_`y'_appended_week_clean.dta, replace
	}
}

foreach x in $lhs {
	foreach y in $rhs {
		gen `x'_`y'_up=beta_`x'_`y'+(2*se_`x'_`y')
		gen `x'_`y'_down=beta_`x'_`y'-(2*se_`x'_`y')
  }
}
  
egen idgroup=group(horizon tenor)  
tsset idgroup end
drop id

save ${temp}analysis_weekly_260.dta, replace

keep start end hor tenor r2_d_cip_rf_d_cip_govt
gen corr=sqrt(r2)
drop r2
keep if hor==260
twoway (line corr end if tenor=="3m") (line corr end if tenor=="1y") (line corr end if tenor=="5y") if end>=tw(2005w1), ///
		legend(order(1 "3 Month" 2 "1 Year" 3 "5 Year") position(6) rows(1))  ///
		xtitle("") ytitle("") yscale(range(0 1)) ylabel (0(0.2)1)
graph export "${graphs}corr_d_cip_rf_d_cip_govt_260_week.png", replace 
}


